const defaultAvatarUrl = "https://api.kuangqiaodongjie.cn/docker_media/picture/avatarUrl/0.png";

Page({
  data: {
    fabu: false,
    login: false,
    avatarUrlTemp: defaultAvatarUrl,
    avatarUrl: defaultAvatarUrl,
    nickNameTemp: "微信用户",
    nickName: "微信用户",
    right: "../../images/right.png",
    down: "../../images/down.png",
    showPageContainer: false,
    showQrcodePopup: false,  // 控制二维码弹窗的显示与隐藏
    qrcodeUrl: "https://api.kuangqiaodongjie.cn/docker_media/files/QR_code/12d6205e2655b7a157eb1325bcdeca0.jpg",  // 后端提供的二维码链接
  },

  onLogin: function(e) {
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: res => {
        this.setData({ login: true });
        wx.login({
          success: res => {
            if (res.code) {
              console.log("openId", res.code);
              this.getSessionKeyAndOpenId(res.code);
            }
          },
        });
      },
      fail: err => {
        console.error("用户拒绝授权：", err);
      }
    });
    wx.showToast({
      icon: "loading",
      title: '正在登录'
    });
  },

  onChooseAvatar(e) {
    const { avatarUrl } = e.detail;
    console.log(avatarUrl);
    this.setData({
      avatarUrlTemp: avatarUrl,
    });
  },

  getNickName(e) {
    if (e.detail.value != "") {
      this.setData({
        nickNameTemp: e.detail.value,
      });
    }
  },

  sendChange() {
    console.log("token in sendChange : ", wx.getStorageSync('token'));
    wx.uploadFile({
      url: 'https://api.kuangqiaodongjie.cn/user/UserInfo/',
      filePath: this.data.avatarUrlTemp,
      name: "avatarUrl",
      header: {
        'Authorization': wx.getStorageSync('token')
      },
      formData: {
        nickName: this.data.nickNameTemp,
      },
      success: res => {
        console.log("res in sendChange : ", res);
        this.setData({
          avatarUrl: this.data.avatarUrlTemp,
          nickName: this.data.nickNameTemp,
        });
        wx.setStorageSync('avatarUrl', this.data.avatarUrlTemp);
        wx.setStorageSync('nickName', this.data.nickNameTemp);
        this.setData({
          showPageContainer: false,
        });
      },
      fail: err => {
        wx.showModal({
          title: '提示',
          content: '昵称或头像不符合要求，请重试。',
          showCancel: false
        });
      }
    });
  },

  cancelChange() {
    this.setData({
      showPageContainer: false,
    });
  },

  getSessionKeyAndOpenId: function(code) {
    wx.request({
      url: 'https://api.kuangqiaodongjie.cn/user/UserLogin/',
      method: 'POST',
      data: { code: code },
      success: res => {
        console.log("res in getSession", res);
        if (res.data && res.data.data && res.data.data.token) {
          wx.setStorageSync('token', res.data.data.token);
          wx.setStorageSync('id', res.data.data.id);
        } else {
          wx.showModal({
            title: '提示',
            content: '登录失败，请重试。',
            showCancel: false
          });
        }

        // 第一次注册需要修改昵称和头像
        if (res.data.isRegister == 0) {
          this.setData({
            showPageContainer: true,
          });
        } else {
          // 已注册用户直接从服务器获取昵称和头像
          wx.request({
            url: 'https://api.kuangqiaodongjie.cn/user/UserInfo/',
            method: 'get',
            header: {
              'Authorization': wx.getStorageSync('token')
            },
            success: res => {
              this.setData({
                avatarUrl: res.data.data.avatarUrl,
                nickName: res.data.data.nickName,
              });
              wx.setStorageSync('avatarUrl', res.data.data.avatarUrl);
              wx.setStorageSync('nickName', res.data.data.nickName);
            },
            fail: err => {
              wx.showModal({
                title: '提示',
                content: '获取用户信息失败，请重试。',
                showCancel: false
              });
            }
          });
        }
      },
      fail: err => {
        console.error("请求服务器登录接口失败：", err);
        wx.showModal({
          title: '错误',
          content: '请求服务器失败，请稍后再试。',
          showCancel: false
        });
      }
    });
  },

  updateIndexPageStatus: function() {
    const pages = getCurrentPages();
    if (pages.length > 1) {
      const indexPage = pages[pages.length - 2];
      if (typeof indexPage.onShow === 'function') {
        indexPage.onShow(); // 调用主页面的 onShow 方法更新状态
      }
    }
  },

  showComingSoon: function() {
    wx.showModal({
      title: '请搜索',
      content: '城子街道矿桥东街社区',
      showCancel: false
    });
  },

  navigateToAbout: function() {
    wx.navigateTo({ url: '../women/women' });
  },

  navigateToFeedback: function(e) {
    wx.navigateTo({ url: '../jianyi/jianyi' });
  },

  navigateToSuggestions: function(e) {
    wx.navigateTo({ url: '../fankuizhuangtai/fankuizhuangtai' });
  },

  // 点击头像时，若头像和昵称为空，显示修改界面
  onChangeAvatar: function() {
    // 如果用户未登录，提示先登录
    if (!this.data.login) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 如果是第一次登录且没有选择头像或昵称，显示修改界面
    if (this.data.nickName === "微信用户" || this.data.avatarUrl === defaultAvatarUrl) {
      this.setData({
        showPageContainer: true,
      });
    }
  },

  onLoad() {
    if (wx.getStorageSync('token')) {
      wx.request({
        url: 'https://api.kuangqiaodongjie.cn/user/UserInfo/',
        method: 'get',
        header: {
          'Authorization': wx.getStorageSync('token')
        },
        success: res => {
          console.log("res in onLoad", res);
          this.setData({
            avatarUrl: res.data.data.avatarUrl,
            nickName: res.data.data.nickName,
            login: true,
          });
          wx.setStorageSync('avatarUrl', res.data.data.avatarUrl);
          wx.setStorageSync('nickName', res.data.data.nickName);
        },
        fail: err => {
          wx.showModal({
            title: '提示',
            content: '您的登录已过期，请重新登录。',
            showCancel: false
          });
        }
      });
    }
  },

  onShow: function() {
    const storedAvatarUrl = wx.getStorageSync('avatarUrl');
    const storedNickName = wx.getStorageSync('nickName');
    // if (storedAvatarUrl && storedNickName) {
    //   this.setData({ avatarUrl: storedAvatarUrl, nickName: storedNickName });
    // } else {
    //   this.setData({ login: false });
    // }
  },

  onPullDownRefresh: function() {},
  onReachBottom: function() {},
  onShareAppMessage: function() {},

  // 显示二维码弹窗
  showQrcode: function() {
    this.setData({
      showQrcodePopup: true,
    });
  },

  // 关闭二维码弹窗
  closeQrcodePopup: function() {
    this.setData({
      showQrcodePopup: false,
    });
  },

  // 处理“社区公众号”点击事件
  navigateToQrcode: function() {
    this.showQrcode();  // 显示二维码弹窗
  },

  // 预览二维码图片
  previewQrcode: function() {
    wx.previewImage({
      current: this.data.qrcodeUrl,  // 当前显示图片的http链接
      urls: [this.data.qrcodeUrl]    // 需要预览的图片http链接列表
    });
  },
});
